package com.Jano.servlet;





import com.Jano.util.RandomUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import static com.Jano.constant.BusinessConstant.*;


/**
 * description: ValidateCodeServlet <br>
 * date: 2022/5/24 8:56 PM <br>
 * author: zoumaoji <br>
 * version: 1.0 <br>
 */
/**
 * 用于动态绘制图形验证码
 */
@WebServlet(urlPatterns = "/validateCode")
public class ValidateCodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession s = req.getSession(false);
        String code = RandomUtils.generateValidateCode(VALIDATE_CODE_LENGTH);
        //将生成的验证码存入Session中，后续用户在操作的时候输入的验指码要和它进行比较
        req.getSession().setAttribute(SESSION_VALIDATE_CODE, code);
        System.out.println("生成的验证码为"+req.getSession().getAttribute(SESSION_VALIDATE_CODE));
        BufferedImage image = RandomUtils.drawValidateCode(code);
        try {
            //设置消息头为输出图片类型
            resp.setContentType("image/png");
            OutputStream os = resp.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
